package com.smart.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ffcs.util.SendRandcode;
import com.forum.util.RegUtil;
import com.smart.model.RanCode;
import com.smart.service.IdentifierCodeService;
import com.smart.service.RanCodeService;
import com.smart.service.UserService;
import com.smart.util.MD5Util;

@RestController
public class RegisterController {
	@RequestMapping(value = "/wechat/get_randCode", method = RequestMethod.POST)
	public void getRandomCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String telephoneNum = req.getParameter("phone");
		System.out.println("community:" + req.getParameter("community"));
		int communityId = Integer.parseInt(req.getParameter("community"));
		System.out.println("telephoneNum:" + telephoneNum + ",communityId:" + communityId);
		int verify = 0;
		UserService userService = new UserService();
		PrintWriter out = null;
		try {
			int userId = userService.getIdByTelephoneNum(telephoneNum, communityId);
			if (userId != -1) {
				System.out.println("将要发送验证码的手机是：" + telephoneNum);
				// 开始向用户的手机发送验证码
				String identifier = SendRandcode.sendSms(telephoneNum);
				if (identifier == null) {
					// 说明获取验证码失败
					verify = 2;
				} else {
					System.out.println("得到的identifier为：" + identifier);
					RanCodeService ranCodeSer = new RanCodeService();
					boolean exist = ranCodeSer.isUserIdExist(userId);
					if (exist) // 已经存在说明不是第一次获取验证码了
					{
						System.out.println("已经存在，说明不是第一次获取验证码了，进行更新identifier");
						if (ranCodeSer.updateIdentifier(identifier, userId) > 0) {
							System.out.println("identifier更新成功");
							verify = 1;
						} else {
							System.out.println("identifier更新失败");
							verify = 2;
						}
					} else {
						System.out.println("以前没有获取过验证码，进行插入");
						if (ranCodeSer.insert(userId, identifier) > 0) {
							System.out.println("identifier插入成功");
							verify = 1;
						} else {
							System.out.println("identifier插入失败");
							verify = 2;
						}
					}
				}
			}
			out = resp.getWriter();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("verify", verify);
			System.out.println(jsonObject);
			out.print(jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null)
				out.close();
		}

		System.out.println("send randomCode finish...");
	}

	@RequestMapping(value = "/wechat/rand_redirect", method = RequestMethod.POST)
	public void RandomCodeRedirect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("验证码转发的响应URL处理");
		String randCode = req.getParameter("rand_code");
		String identifier = req.getParameter("identifier");
		System.out.println("randCode:" + randCode + "," + "identifier:" + identifier);
		IdentifierCodeService identifierCodeSer = new IdentifierCodeService();
		if (identifierCodeSer.insert(identifier, randCode) > 0) {
			System.out.println("验证码插入成功");
		} else {
			System.out.println("验证码插入失败");
		}
		System.out.println("验证码响应URL处理结束");
	}

	@RequestMapping(value = "/wechat/reg", method = RequestMethod.POST)
	public void verify(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("registre method start...");
		UserService userSer = new UserService();
		RanCodeService ranCodeSer = new RanCodeService();
		HttpSession session = req.getSession();
		String communityStr = req.getParameter("community");
		System.out.println("communityStr:" + communityStr);
		int communityId = Integer.parseInt(communityStr);
		String telephoneNum = req.getParameter("phone");
		String code = req.getParameter("randCode");
		System.out.println("telephoneNum:" + telephoneNum + "," + "randCode:" + code + ",communityId:" + communityId);
		Date current = new Date();
		// 通过发过来的手机号去寻找验证码
		int userId = userSer.getIdByTelephoneNum(telephoneNum, communityId);
		System.out.println("获取到的userId:" + userId);
		int result;
		if (userId != -1) {
			IdentifierCodeService identifierCodeSer = new IdentifierCodeService();
			RanCode ranCode = ranCodeSer.getRanCode(userId);
			String identifier = ranCode.getIdentifier();
			String trueCode = identifierCodeSer.getCode(identifier);
			System.out.println("randCode:" + code + "," + "true_randCode:" + trueCode);
			if (code.equals(trueCode)) {
				System.out.println("验证码一样，判断有没有失效");
				long timeTrueCode = ranCode.getCreate_time();
				long timeCode = current.getTime();
				// 两分钟内有效
				float interval = (timeCode - timeTrueCode) / 1000;
				System.out.println("时间间隔为:" + interval + "秒");
				if (interval < 120) {
					System.out.println("验证码未超时");
					result = 1;
				} else {
					System.out.println("验证码超时");
					result = 0;
				}
			} else {
				System.out.println("验证码错误");
				result = 0;
			}

			// 统一清除过期的验证码，过期时间设置为距离现在1小时以后的全部清除
			Date date = new Date();
			long x = date.getTime() - 60 * 60000;
			identifierCodeSer.RmOutDate(new Date(x));
		} else
			result = -1;
		if (result == 1) {
			// 由于想到达这个页面前提肯定是已经授权过了，所以直接获取openId进行注册
			String openId = session.getAttribute("openId").toString();
			String headimgurl = session.getAttribute("headimgurl").toString();
			String nickName = session.getAttribute("nickname").toString();
			System.out.println("telephoneNum:" + telephoneNum + "," + "openId:" + openId);
			// 下面是一些数据库的操作
			if (userSer.regOper(openId, nickName, telephoneNum, communityId)) {
				System.out.println("认证成功！！");
				session.setAttribute("verified", 1);
				// 然后是论坛的数据库进行添加用户操作
				RegUtil.add(openId, headimgurl, nickName);
			} else {
				result = -1;
				System.out.println("认证失败，数据库操作不成功");
			}
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("response", result);
		System.out.println(jsonObject.toString());
		resp.setCharacterEncoding("utf-8");
		PrintWriter out = resp.getWriter();
		out.print(jsonObject.toString());
		System.out.println("register method finish");
	}

	@RequestMapping(value = "/users/register", method = RequestMethod.POST )
	@ResponseBody
	public Map<String, Boolean> register(@RequestParam("phone") String phone,
			@RequestParam("password") String password) {
		System.out.println("client register");
		System.out.println("phone:" + phone + ",password:" + password);
		boolean result = false;
		try {
			UserService userService = new UserService();
			result = userService.userRegister(phone, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.singletonMap("result", result);
	}
}
